<script setup lang="ts">
import type { WritingMode } from '@apps/_share/enums'
import { EventName } from '@apps/_share/enums'
import Layout from '@apps/_share/layouts/default.vue'
import useAppStore from '@apps/_share/store/app'
import useLocaleStore from '@apps/_share/store/locale'
import useMicroStore from '@apps/_share/store/micro'
import { APP_CODE } from './settings'

const isRouterAlive = ref(true)

const route = useRoute()

const appStore = useAppStore()
const localeStore = useLocaleStore()
const microStore = useMicroStore()

if (microStore.getIsMicro) {
  microStore.startWatch(APP_CODE)
}

const isNeedLayout = computed(() => {
  return !['login', '404'].includes(route.name as string) && !microStore.getIsMicro
})

const locale = computed(() => {
  return microStore.getIsMicro
    ? microStore.getLocale
    : localeStore.getLocale
})

function reload() {
  isRouterAlive.value = false
  nextTick(() => {
    isRouterAlive.value = true
  })
}

microStore.getBus.on(EventName.PAGE_REFRESH, ({ appCode }: { appCode: string }) => {
  if (appCode === appStore.getAppCode) {
    reload()
  }
})

if (microStore.getIsMicro) {
  microStore.getBus.on(EventName.SWITCH_WRITING_MODE, (mode: WritingMode) => {
    const html = document.querySelector('html')!
    html.setAttribute('dir', mode)
  })
}
</script>

<template>
  <ElConfigProvider
    :locale="locale"
  >
    <Layout v-if="isNeedLayout">
      <div class="app-main">
        <RouterView
          v-if="isRouterAlive"
          v-slot="{ Component: C }"
        >
          <KeepAlive>
            <Component :is="C" />
          </KeepAlive>
        </RouterView>
      </div>
    </Layout>

    <div
      v-else
      class="app-main"
    >
      <RouterView
        v-if="isRouterAlive"
        v-slot="{ Component: C }"
      >
        <KeepAlive>
          <Component :is="C" />
        </KeepAlive>
      </RouterView>
    </div>
  </ElConfigProvider>
</template>

<style lang="less" scoped>
.app-main {
  overflow: auto;

  block-size: 100%;
}
</style>
